<?php
/**
 * Created by PhpStorm.
 * User: 快定
 * Date: 2021/7/15
 * Time: 13:50
 */

App::uses('Component', 'Controller');

class PublicFunctionComponent extends Component
{

    /**
     * @param $data 加密字段
     * @return string
     */
    function encrypt($data)
    {
        $salt = "123123asdasdasd";
        $psw = md5($salt . md5($data));
        return $psw;
    }

    /**
     * 通用响应
     * @param int $code 响应码
     * @param  string $msg 响应描述
     * @param string $data 响应数据
     */
    function response($code = 200, $msg = "success", $data = array())
    {
        $res = array('code' => $code, 'msg' => $msg, 'data' => $data);
        echo json_encode($res);
        die;
    }

    /**
     * 成功响应
     * @param string $msg 响应描述
     * @param string $data 响应数据
     */
    function success($data = array(), $msg = "success", $code = 200)
    {
        $this->response($code, $msg, $data);
    }

    /**
     * 失败响应
     * @param string $msg 响应描述
     * @param string $data 响应数据
     */
    function fail($code = 500, $msg = "fail")
    {
        $this->response($code, $msg);
    }

    /**
     * 图片上传
     * @param string $name 图片名
     * @param string $dir 上传路径
     */
    function imgUpload($name = "img",$dir)
    {
        $data = $_FILES;
        $allows = array('image/gif', 'image/png', 'image/jpg', 'image/jpeg');
        if (!in_array($data[$name]['type'], $allows)) {
            return false;
        }
        //从文件名中获取文件类型
        $fileTypeArray = explode('.', $data[$name]['name']);
        $fileType = $fileTypeArray[count($fileTypeArray) - 1];
        //设置图片上传的路径
        $filePath = $dir . date('Y-m-d') . '/';
        //没有就递归创建文件夹
        if (!file_exists($filePath)) {
            mkdir($filePath, 0777,true);
        }
        //存储的文件名
        $fileName = time() . rand(1000, 9999);
        $file = $filePath . $fileName . '.' . $fileType;
        $res = move_uploaded_file($data[$name]['tmp_name'], $file);
        $file_url = date('Y-m-d') . '/' . $fileName . '.' . $fileType;
        if ($res) {
            return $file_url;
        }
        return false;
    }

    /**
     * 获取redis实例
     */
    function getRedis()
    {
        App::import('Vendor', 'RedisCurd', array('file' => 'common'.DS.'RedisCurd.php'));
        return RedisCurd::getInstance();
    }

    /**
     * 父子级树状结构 id => pid
     * @param $list
     * @return array
     */
    public function get_tree_list($list)
    {
        //将每条数据中的id值作为其下标
        $temp = [];
        foreach ($list as $v) {
            $v['son'] = [];
            $temp[$v['id']] = $v;
        }
        //获取分类树
        foreach ($temp as $k => $v) {
            $temp[$v['pid']]['son'][] = &$temp[$v['id']];
        }
        return isset($temp[0]['son']) ? $temp[0]['son'] : [];
    }

    /**
     *
     * 过滤输入非安全字符
     *
     * @param $subject array or string ex: $_GET 需要过滤的数组或字符，可以直接传递$_GET/$_POST
     * @param $substr array(key=>value) ex: array('username'=>12, 'desc'=>120) 数组字段允许的最大长度
     * @param $allowhtml bool ex:true 是否允许html标签
     *
     * @return same as origin typeof $subject
     *
     */
    function filterParams($subject, $substr = array(), $allowhtml = true)
    {
        //空字符串
        if (empty($subject) || is_bool($subject) || is_numeric($subject))
            return $subject;

        if (is_array($subject)) {
            foreach ($subject as $key => $val) {
                //数组中存在限制长度的字段
                if (array_key_exists($key, $substr) && is_string($val)) {
                    //截取指定长度
                    $val = mb_substr($val, 0, $substr[$key], 'utf-8');
                }
                //递归执行filterParams方法，将数组全部过滤。
                $subject[$key] = $this->filterParams($val, $substr, $allowhtml);
            }
            return $subject;
        } else {
            //防止xss
            $subject = str_ireplace(";", "", $subject);
            $subject = str_ireplace("&", "&amp;", $subject);
            $subject = str_ireplace("<", "&lt;", $subject);
            $subject = str_ireplace(">", "&gt;", $subject);
            $subject = str_ireplace("'", "", $subject);
            $subject = str_ireplace("--", "", $subject);
		    $subject = str_ireplace("%", "", $subject);
            $subject = str_ireplace("$", "", $subject);
            //防止sql注入
            $subject = str_ireplace("select", "", $subject);
            $subject = str_ireplace("join", "", $subject);
            $subject = str_ireplace("union", "", $subject);
            $subject = str_ireplace("where", "", $subject);
            $subject = str_ireplace("insert", "", $subject);
            $subject = str_ireplace("delete", "", $subject);
            $subject = str_ireplace("update", "", $subject);
            $subject = str_ireplace("like", "", $subject);
            $subject = str_ireplace("drop", "", $subject);
            $subject = str_ireplace("create", "", $subject);
            $subject = str_ireplace("modify", "", $subject);
            $subject = str_ireplace("rename", "", $subject);
            $subject = str_ireplace("alter", "", $subject);
            $subject = str_ireplace("cast", "", $subject);
            //是否允许html标签，不允许去除html标签
            return $allowhtml ? trim($subject) : trim(strip_tags($subject));
        }
    }

    /**
     * 发送curl请求
     * @param $url
     * @param bool $post
     * @param array $params
     * @param bool $https
     * @return bool|string
     */
    function curlRequest($url, $post = true, $params = array(), $https = true)
    {
        //初始化请求会话
        $ch = curl_init($url);
        if ($post) {
            //设置请求方式为post
            curl_setopt($ch, CURLOPT_POST, true);
            //设置请求参数
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        }
        if ($https) {
            //如果是https协议，禁止服务器验证本地证书
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        }
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        //发送请求，获取返回参数
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $res = curl_exec($ch);
        //关闭请求
        curl_close($ch);
        return $res;
    }

    function getAddressByLocation($location)
    {
        $gDMapKey = Configure::read("gDMapKey");
        $LocationToAddress = Configure::read("LocationToAddress");
        $LocationToAddressUrl = $LocationToAddress . "?location={$location}&output=json&key=" . $gDMapKey;
        return $this->curlRequest($LocationToAddressUrl, false);
    }

    function getLocationByAddress($address)
    {
        $gDMapKey = Configure::read("gDMapKey");
        $addressToLocation = Configure::read("addressToLocation");
        $addressToLocationUrl = $addressToLocation . "?address={$address}&output=json&key=" . $gDMapKey;
        return $this->curlRequest($addressToLocationUrl, false);
    }
}